package juc_learn.threadSignal;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class OrderCrossPrint_lock {
	private boolean flag = false;
    private ReentrantLock lock = new ReentrantLock();
    private Condition ca = lock.newCondition();
    
	public void printA(){
		lock.lock();
		try{
			while(flag){
				ca.await();
			}
			for(int i=0;i<5;i++){
				Thread.sleep(100);
				System.out.println(Thread.currentThread().getName()+":"+i);
			}
			flag = true;
			ca.signalAll();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			lock.unlock();
		}
	}
	
	
	public void printB(){
		lock.lock();
		try{
			while(!flag){
				ca.await();
			}
			for(int i=0;i<5;i++){
				Thread.sleep(100);
				System.out.println(Thread.currentThread().getName()+":"+i);
			}
			flag = false;
			ca.signalAll();;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			lock.unlock();
		}
	}
	
	public static void main(String[] args){
		OrderCrossPrint_lock demo = new OrderCrossPrint_lock(); 
		new Thread(()->{
			try {
				Thread.sleep(100);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			demo.printA();
		},"A").start();
		
		new Thread(()->{
			try {
				Thread.sleep(100);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			demo.printB();
		},"B").start();
		
		
		new Thread(()->{
			try {
				Thread.sleep(100);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			demo.printA();
		},"C").start();
		
	}
}
